﻿#region

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Minion.Win.Client.Constants;
using Minion.Win.Client.Helper;
using Minion.Win.Client.Models;
using Newtonsoft.Json;
using RestSharp;

#endregion

namespace Minion.Win.Client.Service.Concrete
{
    public class DataService : IDataService
    {
        public List<Location> GetLocationItems(double lat, double lon)
        {
            var baseApiUri = new Uri(AppSettings.ApiUrlSetting);
            var apiUri = new Uri(baseApiUri, ApiUrl.LocationGet);
            var urlToGet = apiUri.AbsoluteUri.AddToQueryString("json", "true")
                                 .AddToQueryString("lat", lat.ToString(CultureInfo.InvariantCulture))
                                 .AddToQueryString("lon", lon.ToString(CultureInfo.InvariantCulture));

            var task = GetMyData(urlToGet);
            var jsonString = task.Result;
            var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            var streamReader = new StreamReader(memoryStream);
            var serializer = new JsonSerializer();
            var locationsData = (List<Location>) serializer.Deserialize(streamReader, typeof (List<Location>));
            return locationsData;
        }

        public void SaveLocationItem(Location location)
        {
            var restClient = new RestClient(AppSettings.ApiUrlSetting);
            var request = new RestRequest(ApiUrl.LocationPost, Method.POST) {RequestFormat = DataFormat.Json};
            request.AddBody(location);
            restClient.ExecuteAsync(request, response =>
                {
                    var test = response;
                });
              
        }

        public async Task<string> GetMyData(string urlToCall)
        {
            var request = (HttpWebRequest) WebRequest.Create(urlToCall);
            request.Method = HttpMethod.Get;
            HttpWebResponse response = await request.GetResponseAsync();
            using (var sr = new StreamReader(response.GetResponseStream()))
            {
                return sr.ReadToEnd();
            }
        }
    }

    public static class HttpMethod
    {
        public static string Head
        {
            get { return "HEAD"; }
        }

        public static string Post
        {
            get { return "POST"; }
        }

        public static string Put
        {
            get { return "PUT"; }
        }

        public static string Get
        {
            get { return "GET"; }
        }

        public static string Delete
        {
            get { return "DELETE"; }
        }

        public static string Trace
        {
            get { return "TRACE"; }
        }

        public static string Options
        {
            get { return "OPTIONS"; }
        }

        public static string Connect
        {
            get { return "CONNECT"; }
        }

        public static string Patch
        {
            get { return "PATCH"; }
        }
    }

    public static class HttpExtensions
    {
        public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
        {
            var taskComplete = new TaskCompletionSource<HttpWebResponse>();
            request.BeginGetResponse(asyncResponse =>
                {
                    try
                    {
                        var responseRequest = (HttpWebRequest) asyncResponse.AsyncState;
                        var someResponse = (HttpWebResponse) responseRequest.EndGetResponse(asyncResponse);
                        taskComplete.TrySetResult(someResponse);
                    }
                    catch (WebException webExc)
                    {
                        var failedResponse = (HttpWebResponse) webExc.Response;
                        taskComplete.TrySetResult(failedResponse);
                    }
                }, request);
            return taskComplete.Task;
        }
    }
}